<template>
  <div class="main">

    <el-text tag="b" size="large">基本信息</el-text>
    <el-row>
      <el-form ref="orderDataRef" :model="orderData.order" :inline="true" :rules="orderDataRules">
        <el-form-item label="入库类型:" prop="typeId">
          <el-select :disabled="!isNew" v-model="orderData.order.typeId" style="width: 160px" clearable>
            <el-option v-for="(item, index) in fieldList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <!-- <el-text v-else>{{ fieldList.find(item => item.id === orderData.order.typeId).name }}</el-text> -->
        </el-form-item>
        <el-form-item label="仓库名称:" prop="whId">
          <el-select :disabled="!isNew" v-model="orderData.order.whId" style="width: 240px" clearable>
            <el-option v-for="(item, index) in whlist" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <!-- <el-text v-else>{{ whlist.find(item => item.id === orderData.order.whId).name }}</el-text> -->
        </el-form-item>
        <el-form-item label="供应商名称:" prop="vendorId">
          <el-select :disabled="!isNew" v-model="orderData.order.vendorId" style="width: 240px" clearable>
            <el-option v-for="(item, index) in vendorList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <!-- <el-text v-else>{{ vendorList.find(item => item.id === orderData.order.vendorId).name }}</el-text> -->
        </el-form-item>
      </el-form>
    </el-row>
    <el-text tag="b" size="large">备注</el-text>
    <el-row>
      <el-input :disabled="!isNew" type="textarea" v-model="orderData.order.remark" :rows="3" maxlength="255"
        show-word-limit style="width: calc(100vw - 400px)"></el-input>
      <!-- <el-text>{{ orderData.order.remark }}</el-text> -->
    </el-row>
    <el-text tag="b" size="large">附件</el-text>
    <el-button v-if="isNew" type="primary" :icon="Plus" size="small" style="margin-left: 56px;">新增</el-button>
    <el-row></el-row>
    <el-text tag="b" size="large">物料信息</el-text>
    <el-button v-if="isNew" type="primary" :icon="Plus" size="small" style="margin-left: 24px;"
      @click="showProductSelect = true">新增</el-button>
    <el-row>
      <el-table class="table" :data="details">
        <el-table-column align="center" label="序号" type="index" width="80"></el-table-column>
        <el-table-column align="center" label="物料名称" prop="name"></el-table-column>
        <el-table-column align="center" label="物料编号" prop="code"></el-table-column>
        <el-table-column align="center" label="规格型号" prop="model"></el-table-column>
        <el-table-column align="center" label="数量">
          <template #default="{ row }">
            <el-input v-if="isNew" type="number" v-model="row.quantity" min="0"></el-input>
            <el-text v-else>{{ row.quantity }}</el-text>
          </template>

        </el-table-column>
        <el-table-column align="center" label="单位" prop="unit"></el-table-column>
        <el-table-column align="center" label="备注" prop="remark"></el-table-column>
        <!-- <el-table-column align="center" label="总价" prop=""></el-table-column> -->
        <el-table-column v-if="isNew" align="center" label="操作">
          <template #default="{ row }">
            <el-button type="danger" :icon="Delete" @click="delItem(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row v-if="isNew" class="footer">
      <div>
        <el-button type="primary" plain @click="router.push({ path: '/equipment/inbound' })">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </el-row>

  </div>
  <el-drawer v-model="showProductSelect" title="编辑物料信息" direction="rtl" size="60%">
    <ProductSelect :product-selected="details" @close="handleClose" @confirm="handleConfirm"></ProductSelect>
  </el-drawer>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, watch } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue';
import { getInboundFieldList } from '@/utils/commonData'
import { getWhlist, getVendorList } from '@/api/setting'
import { addInbound, getInboundOrderAndDetail } from '@/api/equipment/whm'
import ProductSelect from '../../components/ProductSelect.vue';
const route = useRoute()
const router = useRouter()
const batchno = route.params?.batchno
const isNew = batchno === 'new'
const orderDataRef = ref(null)
/**入库类型 */
const fieldList = ref([])
getInboundFieldList().then(res => fieldList.value = res)
/** 获取仓库列表 */
const whlist = ref([])
const doGetWhlist = async () => {
  await getWhlist('备品备件').then(res => {
    if (res.data.data.length === 0) {
      ElMessage.error('无可管理仓库,返回列表')
      router.back()
      return
    }
    whlist.value = res.data.data
  })
}
doGetWhlist()
/** 获取vendor列表 */
const vendorList = ref([])
getVendorList().then(res => vendorList.value = res.data.data.filter(item => item.type === 'vendor'))

/** Data数据 */
const details = ref([])
const orderData = ref({
  order: {
    id: null,
    batchno: null,
    typeId: null,
    vendorId: null,
    whId: null,
    remark: null,
    attach: null,
  },
  details: [
    // {
    // id: 1,
    // name: '1',
    // code: 'code',
    // model: 'mode',
    // typeId: 2,
    // categoryId: 2,
    // unit: 'unit',
    // remark: 'remark',
    // quantity: 20,
    // }
  ]
})
/** Rules */
const orderDataRules = ref({
  typeId: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  vendorId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  whId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
})
function delItem(row) {
  details.value = details.value.filter(item => item.id !== row.id)
}
/** 抽屉，选择product */
const showProductSelect = ref(false)
function handleClose() {
  showProductSelect.value = false
}
function handleConfirm(product) {
  console.log('product', product)
  details.value = product
  showProductSelect.value = false
}
/** 查询数据 */
async function getInboundDetail() {
  await getInboundOrderAndDetail(batchno).then(res => {
    console.log('getInboundDetail', res)
    orderData.value.order = res.data.data.order
    details.value = res.data.data.details
  })
}
if (!isNew) {
  getInboundDetail()
}
/** 新增入库单 */
async function confirm() {
  if (orderData.value.details.length === 0) {
    ElMessage.error('请添加物料信息')
    return
  }
  orderDataRef.value.validate((valid) => {
    if (valid && orderData.value.details.every(item => item.quantity > 0)) {
      if (isNew) {
        ElMessageBox.alert('提交入库单后将无法修改，是否确认提交？', '确认提交',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            // center: true,
            // appendTo: document.querySelector("#app")
          }
        ).then(async () => {
          await addInbound(2, orderData.value).then(res => {
            ElMessage.success(res.data.data)
            router.push({ path: '/equipment/inbound' })
          })
        }
        )
      } else {
        console.log('修改入库单')
      }
    } else {
      ElMessage.error('请完善信息')
    }
  }
  )
}

watch([details],
  () => {
    orderData.value.details = []
    details.value.forEach(item => {
      let detail = {}
      detail.productId = item.id
      detail.quantity = item.quantity
      orderData.value.details.push(detail)
    })
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="less">
.footer {
  width: 100%;

  div {
    width: 260px;
    margin: 0 auto;
  }
}

.el-row {
  margin: 12px 24px;
}

:deep(th.el-table__cell) {
  background-color: var(--el-color-primary-light-7) !important;
}
</style>